﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using RBAC.ApiReads.Application.Command;
using RBAC.ApiReads.DTO;
using RBAC.Domain.RbacEntity;
using RBAC.Infrasturcture.Interfaces;
using RBAC.ResultCode;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RBAC.ApiReads.Application.Commandhandler
{
    public class GetUserRoleCommandCommandhandler : IRequestHandler<GetUserRoleCommand, ApiResult<ApiPaging<List<UserRoleDTO>>>>
    {
        private readonly IBaseRepository<User> userrepository;
        private readonly IBaseRepository<Role> rolerepository;
        private readonly IBaseRepository<UserRole> userrolerepository;
        private readonly IMapper mapper;

        public GetUserRoleCommandCommandhandler(IBaseRepository<User> userrepository,IBaseRepository<Role> rolerepository,IBaseRepository<UserRole> userrolerepository,IMapper mapper)
        {
            this.userrepository = userrepository;
            this.rolerepository = rolerepository;
            this.userrolerepository = userrolerepository;
            this.mapper = mapper;
        }
        public async Task<ApiResult<ApiPaging<List<UserRoleDTO>>>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {

            var info =  userrepository.GetAll();
            if (!string.IsNullOrEmpty(request.UserName))
            {

                info = info.Where(x => x.UserName == request.UserName);
            }
            //总条数
            int TotalCount = info.Count();
            //总页数
            int TotalPage = (int)Math.Ceiling(1.0 * TotalCount / request.PageSize);
            //数据
            var list = info.OrderBy(x => x.UserId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            var data =mapper.Map<List<UserRoleDTO>>(list);

            //显示的是角色权限的信息  根据角色id查中间表的权限id 因为是一个角色多个权限所以得用循环
            foreach (var item in data) 
            {
                var roleIdlist = userrolerepository.GetAll().Where(x=>x.UserId==item.UserId).Select(x=>x.RoleId).ToList();
                item.RoleId= roleIdlist;
                var rolelist = rolerepository.GetAll().Where(x => roleIdlist.Contains(x.RoleId)).Select(x=>x.RoleName).ToList();
                item.RoleName = rolelist;
            }
            return new ApiResult<ApiPaging<List<UserRoleDTO>>>
            {
                Code = ApiResultEnum.查询成功,
                Message = ApiResultEnum.查询成功.ToString(),
                Data = new ApiPaging<List<UserRoleDTO>>
                {
                    Data = data,
                    TotalCount = TotalCount,
                    TotalPage = TotalPage,
                }

            };

        }


    }
}
